import {getLocalItem} from "../util/Utils.js";
import {SceneConfig} from "../lib/CommonConsts.js";
import ModelVO from "../entity_vo/ModelVO.js";
import ModelEntity from "../entity/ModelEntity.js";
import * as THREE from "../../../modules/three/three.module.js";
import AircraftEntity from "../entity/AircraftEntity.js";
import {ModelBreakable, ModelBreakableEntity} from "../entity/ModelBreakableEntity.js";

export async function getJsonData() {
  try {
    // 3d/plan/plan2.json , https://static.hcytech.com.cn/3D/3d.json
    const response = await fetch("../public/3d/plan/plan4.json", {
      cache: "no-cache", // 设置不使用缓存
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error:", error);
    return getLocalItem(SceneConfig.localSaveName);
  }
}

// 三维场景的数据中心
export default class MainStore {
  gltfSceneMap = new Map();
  _initialEyePos = new THREE.Vector3();
  _initialFocus = new THREE.Vector3();
  /**
   * @type {ModelEntity}
   * 无人机
   */
  UAV = []
  /**
   * 模型列表
   * @type {ModelEntity[]}
   */
  models = []
  /**
   * @type {AircraftEntity}
   */
  aircraft

  constructor() {}

  /**
   *
   * @param obj
   * @param {Scene3d} scene3d
   */
  storageLoad(obj, scene3d) {
    obj.models.forEach(modelObj => {
      const modelVO = new ModelVO().fromJsonObj(modelObj);
      let modelEntity
      if (modelVO.url.endsWith('FeiJi_ok.glb')) {
        modelEntity = new AircraftEntity(modelVO, this.gltfSceneMap)
        this.aircraft = modelEntity
        scene3d.focusToPosition(modelEntity.position)
      } else {
        modelEntity = new ModelEntity(modelVO, this.gltfSceneMap);
      }
      scene3d.scene.add(modelEntity);
      this.models.push(modelEntity);
    });
    // if (obj.sceneCamera) {
    //   const eye = new THREE.Vector3().fromArray(obj.sceneCamera.eye);
    //   const focus = new THREE.Vector3().fromArray(obj.sceneCamera.focus);
    //   scene3d.camera.position.copy(eye);
    //   scene3d.setCameraFocus(focus);
    //   scene3d.cameraControls.update();
    //   this._initialEyePos.copy(eye);
    //   this._initialFocus.copy(focus);
    // }
  }
}
